/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.yuecai.modules.yc_category.service;


import com.yuecai.modules.yc_category.domain.YcCategory;
import com.yuecai.modules.yc_category.repository.YcCategoryRepository;
import com.yuecai.modules.yc_category.service.dto.YcCategoryDto;
import com.yuecai.modules.yc_category.service.dto.YcCategoryQueryCriteria;
import com.yuecai.modules.yc_category.service.mapstruct.YcCategoryMapper;
import com.yuecai.modules.yc_category.vo.YcCategoryVo;
import com.yuecai.utils.FileUtil;
import com.yuecai.utils.PageUtil;
import com.yuecai.utils.QueryHelp;
import com.yuecai.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author dm
* @date 2020-06-24
**/
@Service
@RequiredArgsConstructor
public class YcCategoryService {

    private final YcCategoryRepository ycCategoryRepository;
    private final YcCategoryMapper ycCategoryMapper;

    
    public Map<String,Object> queryAll(YcCategoryQueryCriteria criteria, Pageable pageable){
        Page<YcCategory> page = ycCategoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(ycCategoryMapper::toDto));
    }

    
    public List<YcCategoryDto> queryAll(YcCategoryQueryCriteria criteria){
        return ycCategoryMapper.toDto(ycCategoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    
    @Transactional
    public YcCategoryDto findById(Long id) {
        YcCategory ycCategory = ycCategoryRepository.findById(id).orElseGet(YcCategory::new);
        ValidationUtil.isNull(ycCategory.getId(),"YcCategory","id",id);
        return ycCategoryMapper.toDto(ycCategory);
    }

    
    @Transactional(rollbackFor = Exception.class)
    public YcCategoryDto create(YcCategory resources) {
        return ycCategoryMapper.toDto(ycCategoryRepository.save(resources));
    }

    
    @Transactional(rollbackFor = Exception.class)
    public void update(YcCategory resources) {
        YcCategory ycCategory = ycCategoryRepository.findById(resources.getId()).orElseGet(YcCategory::new);
        ValidationUtil.isNull( ycCategory.getId(),"YcCategory","id",resources.getId());
        ycCategory.copy(resources);
        ycCategoryRepository.save(ycCategory);
    }

    
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            ycCategoryRepository.deleteById(id);
        }
    }

    
    public void download(List<YcCategoryDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (YcCategoryDto ycCategory : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("分类名称", ycCategory.getName());
            map.put("图标", ycCategory.getPic());
            map.put("分类状态1.启用 0禁用", ycCategory.getStatus());
            map.put("分类排序", ycCategory.getSort());
            map.put("添加时间", ycCategory.getCreateTime());
            map.put("修改时间", ycCategory.getUpdateTime());
            map.put("上级分类Id （一级分类为空）", ycCategory.getUpId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    public List<YcCategory> findByUpIdNotNull() {
        List<YcCategory> yc = ycCategoryRepository.findByUpIdIsNotNullAndStatusTrueOrderBySort();
        return yc;
    }
    public List<YcCategory> findByUpIdIsNull() {
        List<YcCategory> yc = ycCategoryRepository.findByUpIdIsNullAndStatusTrueOrderBySort();
        return yc;
    }

    public ResponseEntity<Object> tree() {
        List<YcCategory> yc = ycCategoryRepository.findByUpIdIsNullAndStatusTrueOrderBySort();
        List<YcCategoryVo> ycCategoryVos = treeC(yc);
        return ResponseEntity.ok(ycCategoryVos);
    }

    public List<YcCategoryVo> treeC(List<YcCategory> yc){
        List<YcCategoryVo> vos = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(yc)){
            for (YcCategory ycCategory : yc) {
                Long id = ycCategory.getId();
                YcCategoryVo vo = new YcCategoryVo();
                BeanUtils.copyProperties(ycCategory,vo);
                List<YcCategory> list = ycCategoryRepository.findByUpIdAndStatusTrueOrderBySort(id);
                if (CollectionUtils.isNotEmpty(list)){
                    List<YcCategoryVo> ycCategoryVos = treeC(list);
                    vo.setCategories(ycCategoryVos);
                }
                vos.add(vo);
            }
            return vos;
        }
        return null;
    }


    public ResponseEntity<Object> optionGroup() {
        List<YcCategory> yc = ycCategoryRepository.findByUpIdIsNullAndStatusTrueOrderBySort();
        List<HashMap<Long,String>> vos = new ArrayList<>();
        for (YcCategory ycCategory : yc) {
            Long id = ycCategory.getId();
            HashMap vo = new HashMap<Long,String>();
            vo.put("label",ycCategory.getName());
            List<YcCategory> list = ycCategoryRepository.findByUpIdAndStatusTrueOrderBySort(id);
            List<HashMap> options = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(list)){
                for (YcCategory category : list) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("value",category.getId());
                    map.put("label",category.getName());
                    options.add(map);
                }
            }
            vo.put("options",options);
            vos.add(vo);
        }
        HashMap<Object, Object> map = new HashMap<>();
        map.put("options",vos);
        return ResponseEntity.ok(map);
    }
}